﻿using System;
using System.Collections;
using UnityEngine;

public class UINodeTransformComponent : MonoBehaviour {

    public static UINodeTransformComponent thas;

    [SerializeField]
    Transform nodeGrid;

    [SerializeField]
    UIGrid scrollView;

    [SerializeField]
    UIItemTransformUnitDrawVoxelComponent itemTransformDrawVoxelUnitPrefab;

    //[SerializeField]
    //public UIItemTransformUnitDrawVoxelComponent itemTransformDrawVoxelUnitPrefad;

    [SerializeField]
    UIItemTransformUnitComponent itemTransformUnitPrefab;

    [SerializeField]
    UIItemTransformUnitBoneComponent itemTransformUnitBonePrefab;

    [SerializeField]
    public GameObject itemTransformUnitBoneGameObjectPrefab;

    void Awake()
    {
        thas = this;
    }
    //UIItemTransformUnitComponent
    public TransformUnitComponent AddItem (string name, Vector3 position, Vector3 minPosition, Transform unit , Type T,out UIItemTransformUnitComponent tranItem)
    //where T : UIItemTransformUnitComponent
    {
        tranItem = null;
        if (T == typeof(UIItemTransformUnitDrawVoxelComponent))
        {
            tranItem = Instantiate(itemTransformDrawVoxelUnitPrefab);
        }
        else if (T == typeof(UIItemTransformUnitBoneComponent))
        {
            tranItem = Instantiate(itemTransformUnitBonePrefab);
        }
        else
        {
            tranItem = Instantiate(itemTransformUnitPrefab);
        }
        if (tranItem != null)
        {
            tranItem.Show(name, position, unit);
            tranItem.transform.SetParent(nodeGrid);
            tranItem.transform.localScale = new Vector3(1, 1, 1);

            TransformUnitComponent tTransformUnitComponent = unit.gameObject.AddComponent<TransformUnitComponent>();
            tTransformUnitComponent.Show(tranItem, position, minPosition);

            Reposition();
            return tTransformUnitComponent;
        }
        else
        {
            return null;
        }
        //if (this.enabled)
        //{
        //    StartCoroutine(ScrollViewReposition());
        //}
    }

    public void Reposition()
    {
        scrollView.enabled = true;
        scrollView.repositionNow = true;
        scrollView.Reposition();
    }
    private IEnumerator ScrollViewReposition()
    {
        yield return new WaitForSeconds(0.1f);
        //yield return new WaitForEndOfFrame();
        Reposition();
    }
}
